# -*- coding:utf-8 -*-
__author__ = 'gin.chen'


## 单链表

class Node:
    def __init__(self, x):
        self.val = x
        self.next = None


class ListLink:
    def __init__(self, data=None):
        if data is not None:
            data = list(data)
            self.head = Node(data[0])
            p = self.head
            for i in data[1:]:
                p.next = Node(i)
                p = p.next

    def get_heap(self):
        return self.head

    def set_heap(self,head):
        self.head = head

    # 尾插法
    def insert(self, index, value):
        if index < 0 or index > self.get_length():
            print "Index is error!"
            return

        p = self.head
        j = 0
        while p is not None and j < index:
            j += 1
            p = p.next

        node = Node(value)
        node.next = p.next.next
        p.next = node

    def get_item(self, index):
        p = self.head
        j = 0
        while p is not None and j < index:
            j += 1
            p = p.next
        return p.val

    def delete(self, index):
        p = self.head
        j = 0
        # pre = None
        while p is not None and j < index - 1:
            j += 1
            p = p.next

        pre = p
        pre.next = pre.next.next

    def update(self, index, value):
        p = self.head
        j = 0
        while p is not None and j < index:
            j += 1
            p = p.next
        p.val = value

    def show(self):
        p = self.head
        while p is not None:
            print p.val
            p = p.next

    def get_length(self):
        p = self.head
        length = 0
        while p is not None:
            length += 1
            p = p.next
        return length


if __name__ == '__main__':
    xx = ListLink([1, 2, 3, 4, 5, 6])
    # print  xx.get_item(3)
    xx.update(3, 8)
    # print  xx.get_item(3)
    # xx.show()
